//! Command system for the Rust Collector.
//!
//! This module provides a command broadcasting system that allows different
//! components to communicate through command signals like LinkUp and LinkDown.
//! 
//! - LinkUp will trigger Exporter load the persistent data into memory queue and sending data.
//! - LinkDown will trigger Exporter stop sending and destroy the memory queue.

use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;

pub mod service;

/// Enum representing possible commands for the system.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum Command {
    /// Communication window is open.
    LinkUp,
    /// Communication window is closed.
    LinkDown,
}

/// Command broadcaster
/// 
/// Passing command signals between components.
pub struct CommandBroadcaster {
    sender: broadcast::Sender<Command>,
}

impl CommandBroadcaster {
    /// Creates a new CommandBroadcaster instance.
    pub fn new() -> Self {
        let (sender, _) = broadcast::channel(100);
        Self { sender }
    }

    /// Sends a command through the broadcaster.
    pub fn send_command(
        &self,
        command: Command,
    ) -> Result<usize, broadcast::error::SendError<Command>> {
        self.sender.send(command)
    }

    /// Subscribes to receive commands.
    pub fn subscribe(&self) -> broadcast::Receiver<Command> {
        self.sender.subscribe()
    }

    /// Returns the number of active receivers.
    pub fn receiver_count(&self) -> usize {
        self.sender.receiver_count()
    }
}

impl Default for CommandBroadcaster {
    fn default() -> Self {
        Self::new()
    }
}
